import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;


public class Parse {
	private static final String MOVIE_OUTPUT = "movies\\";
	private static final String USER_OUTPUT = "users\\";
	private static final String TRAINING_SET = "training_set\\";
	
	public Parse() {
	}
	
	public void parse(String address) {
		File file = new File(address);
		
	    try {
    		BufferedReader reader = new BufferedReader(new FileReader(file));
	    	try {
	    		String temp = null;
	    		temp = reader.readLine();
	    		String[] firstLine = temp.split(":");
	    		int movieNumber = Integer.parseInt(firstLine[0]);
	    		FileWriter moviePrinter;
	    		moviePrinter = new FileWriter(new File(MOVIE_OUTPUT+"mv_"+movieNumber+".txt"), true);

	    		while ((temp=reader.readLine())!=null) {
	    			String[] line = temp.split(",");
	    			int userId = Integer.parseInt(line[0]);
	    			int rating = Integer.parseInt(line[1]);
	    			
	    			FileWriter userPrinter = new FileWriter(new File(USER_OUTPUT+"usr_"+userId+".txt"), true);
	    			
	    			String ret = "";
	    			for(int i=0; i<line.length-1;i++) {
	    				ret+=line[i];
	    				if(i<line.length-2) ret+=",";
	    			}
	    			moviePrinter.write(ret+"\n");
	    			userPrinter.write(movieNumber+","+rating+"\n");
		    		userPrinter.close();
	    		}
	    		moviePrinter.close();
	    	} finally {
		    	reader.close();
		    }
	    } catch (IOException ex) {
	    	System.out.println("file does not exist");
	    }
	}
	
	public void run(int numMovies) {
		for(int i=1; i<=numMovies;i++){
			parse(getAddress(i));
			if(i%5==0) {
				System.out.println(i+"done...");
			}
		}
	}
	
	public String getAddress(int number) {
		String ret = ""+number;
		int numZeroes = 7 - ret.length();
		for(int i=1; i<=numZeroes;i++) {
			ret = "0" + ret;
		}
		return TRAINING_SET+"mv_"+ret+".txt";
	}
	
	public static void main(String[] args) throws FileNotFoundException {
		long st = System.currentTimeMillis();	
		Parse p = new Parse();
		p.run(10);
		System.out.println("Time used: "+(System.currentTimeMillis()-st)/1000.0 +"s");
	}
}
